package com.towexin.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

/**
 * TODO
 *
 * MybatisPlus 字段自动填充策略
 *
 * @author Towexin
 * @version 1.0
 * @date 2021/4/8 11:14
 */
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    private static final Logger LOGGER= LoggerFactory.getLogger(MyBatisPlusMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        //拿到createdTime的值
        Object nickname = getFieldValByName("nickname", metaObject);
        Object status = getFieldValByName("status", metaObject);
        Object created_time = getFieldValByName("createdTime", metaObject);
        //插入时填充创建时间 fieldName是属性名
        LOGGER.info("insert 自动填充 "+ LocalDateTime.now());// setInsertFieldValByName("createTime", LocalDateTime.now(),metaObject);

        if(metaObject.hasSetter("createdTime")){//有set方法
            if (created_time == null || created_time.equals("")) {//值为null填充
                setFieldValByName("createdTime", new Date(), metaObject);
            }
        }
        if(metaObject.hasSetter("nickname")){
            if (nickname == null || nickname.equals("")) {
                setFieldValByName("nickname", "用户_" + UUID.randomUUID().toString().replace("-", "").substring(0, 10), metaObject);
            }
        }
        if(metaObject.hasSetter("status")){
            if (status == null || status.equals("")) {
                setFieldValByName("status", Boolean.TRUE, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object update_time = getFieldValByName("updateTime", metaObject);
        //修改时填充当前时间  fieldName是属性名
        LOGGER.info("update 自动填充 "+ LocalDateTime.now());
        //setUpdateFieldValByName("updateTime", LocalDateTime.now(),metaObject);
        if (metaObject.hasSetter("updateTime")){
            if (update_time == null || update_time.equals("")) {
                setFieldValByName("updateTime", new Date(), metaObject);
            }
        }
    }
}
